Skip to main content

Chapter 12 - Count

Creating multiple resources just by incrementing the count.

Count


Count is creating multiple instances of a resource - repeating. You may need to use count.index to increment the number of the resources.

  • Cannot use foreach and count at the same time.
  • RG1, RG2, RG3, etc.

Create multiple RGs


resource "azurerm_resource_group" "myrg" {
count = 3
name = "myrg-${count.index}"
location = "East US"
}

Create multiple linux VMs


Splat Expressions Terraform console commands

  • element
  • length

In order to take a count and translate into a place where you can't use count.index, use splatting to select from a group of items what the index is to match the count.index for the entire thing.

Reading through 11.02 in the course github will help. Notice the changes to v2 that create multiple instances.

resource "azurerm_network_interface" "myvmnic" {
count =2
name = "vmnic-${count.index}"
location = azurerm_resource_group.myrg.location
resource_group_name = azurerm_resource_group.myrg.name

ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.mysubnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = element(azurerm_public_ip.mypublicip[*].id, count.index) # this line here
}
}